﻿using System;
using System.Collections.Generic;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using WhallaToolkit.ShareServices.Helpers;
using WhallaToolkit.ShareServices.Models;

namespace WhallaToolkit.ShareServices.Brokers.Facebook
{
    internal sealed partial class FacebookConnect
    {

        #region Fields

        private string RequestTokenVerifier = "";
        private string responseData = "";
        private uint responseErrorDetail = 0;
        private string authenticationCode = "";
        private WebAuthenticationStatus responseStatus = WebAuthenticationStatus.UserCancel;

        private bool authenticationStarted = false;
        private bool authenticationFinished = false;

        #endregion


        #region Constructor

        public FacebookConnect()
        {
            InitializeComponent();

            BrowserControl.ClearCookiesAsync();
            BackKeyPress += FacebookConnect_BackKeyPress;
            BrowserControl.Navigating += BrowserControl_Navigating;
            BrowserControl.NavigationFailed += BrowserControl_NavigationFailed;
            BrowserControl.LoadCompleted+=BrowserControl_LoadCompleted;
        }

        #endregion


        #region Events

        void FacebookConnect_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            responseData = "";
            responseStatus = WebAuthenticationStatus.UserCancel;

            authenticationFinished = true;
        }


        #region Browser

        private void BrowserControl_NavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            WebBrowserNavigationException navEx = e.Exception as WebBrowserNavigationException;

            if (navEx != null)
            {
                // Pass along the provided error information.
                responseErrorDetail = (uint)navEx.StatusCode;
            }
            else
            {
                // No error information available.
                responseErrorDetail = 0;
            }
            responseStatus = WebAuthenticationStatus.ErrorHttp;

            authenticationFinished = true;
            e.Handled = true;

            // Navigate back now.
            BrowserControl.Source = new Uri("about:blank");
            NavigationService.GoBack();
        }

        void BrowserControl_Navigating(object sender, NavigatingEventArgs e)
        {
            if (e.Uri.LocalPath == FacebookAuthenticationBroker.EndUri.LocalPath)
            {
                String queryString = e.Uri.Query;

                // Acquire the code from Query String
                IEnumerable<KeyValuePair<string, string>> pairs = queryString.ParseQueryString();
                authenticationCode = pairs.GetValue("code");

                responseData = e.Uri.ToString();
                responseStatus = WebAuthenticationStatus.Success;
                authenticationFinished = true;

                BrowserControl.Source = new Uri("about:blank");
                NavigationService.GoBack();
            }
        }

        private void BrowserControl_LoadCompleted(object sender, NavigationEventArgs e)
        {
            CloseLoadingIndicator.Begin();
        }

        #endregion


        #region Navigation

        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            // If there is an active authentication operation in progress and we have
            // finished, then we need to inform the authentication broker of the results.
            // We don't want to stop the operation prematurely, such as when navigating to
            // the start screen.
            if (FacebookAuthenticationBroker.AuthenticationInProgress && authenticationFinished)
            {
                authenticationStarted = false;
                authenticationFinished = false;
                FacebookAuthenticationBroker.OnAuthenticationFinished(responseData, responseStatus, responseErrorDetail, authenticationCode);
            }
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Make sure that there is an authentication operation in progress.
            // If not, we'll navigate back to the previous page.
            if (!FacebookAuthenticationBroker.AuthenticationInProgress)
            {
                this.NavigationService.GoBack();
            }

            if (!authenticationStarted)
            {
                authenticationStarted = true;
                authenticationFinished = false;

                // Point the browser control to the authentication start page.
                BrowserControl.Source = FacebookAuthenticationBroker.StartUri;
            }
            base.OnNavigatedTo(e);
        }

        #endregion

        #endregion

    }
}